import { _decorator, Component, Label, Node, ProgressBar } from 'cc';
import EventManager from '../Managers/EventManager';
import { EventTypes } from '../Managers/EventTypes';
const { ccclass, property } = _decorator;

// 初始场景加载的进度UI
@ccclass('InitUI')
export class InitUI extends Component {
    @property(ProgressBar)
    progressBar: ProgressBar = null;
    @property(Node)
    initInfo: Node = null;
    @property(Label)
    progressLabel: Label = null;

    curProgress = 0;
    initToProgress = 0.6;
    toProgress = 0.6;
    progressSpd = 0.2;
    // 最小显示时间
    minTime = 1;
    curTime = 0;
    loadProgress = 0;
    isFinish = false;

    onLoad() {
        EventManager.on(EventTypes.GameEvents.SetInitUIEnable, this.onSetInitUIEnable, this);
        EventManager.on(EventTypes.GameEvents.InitLoadFinished, this.InitLoadFinished, this);
        // 只显示一次的信息
        this.initInfo.active = true;
    }

    public show(d?) {
        this.node.active = true;

        this.curProgress = 0;
        this.toProgress = this.initToProgress;
        this.progressBar.progress = 0;
        this.progressLabel.string = '0';

        this.curTime = 0;
        this.loadProgress = 0;
    }

    public hide(d?) {
        this.node.active = false;
    };

    protected update(dt: number): void {
        if (this.isFinish) {
            return;
        }
        // 限制最小显示时长
        this.curTime += dt;
        if (this.curTime < this.minTime) {
            this.toProgress = this.initToProgress;
        } else {
            this.toProgress = this.loadProgress;
        }
        // 进度条
        let r = this.curProgress / this.toProgress;
        r = Math.min(r, 1);
        let spd = this.progressSpd;
        // 速度减慢
        if (this.toProgress < 1) {
            spd = (1 - r) * this.progressSpd;
        } else {
            spd = 1;
        }
        let step = spd * dt;
        this.curProgress = Math.min(this.curProgress + step, 1);
        this.progressBar.progress = this.curProgress;

        this.progressLabel.string = (this.curProgress * 100).toFixed();
        if (this.curProgress >= 1) {
            // 加载结束
            this.onLoadFinish();
        }
    }

    onLoadFinish() {
        this.isFinish = true;
        this.initInfo.active = false;
        // this.hide();
        EventManager.emit(EventTypes.GameEvents.InitFinished);
    }

    onSetInitUIEnable(isEnable) {
        if (undefined == isEnable) return;
        isEnable && this.show();
        !isEnable && this.hide();
    }

    InitLoadFinished() {
        this.loadProgress = 1;
        console.log('# InitLoadFinished')
    }


}

